
package com.sausageking.server;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Strings;
import com.sausageking.server.common.ServerUtil;
import com.sausageking.server.dao.GenericDao;
import com.sausageking.shared.Checkin;
import com.sausageking.shared.Constants;

@Deprecated
public class FacebookRedirectServlet extends HttpServlet {

  private static final long serialVersionUID = 5756406341012899888L;

  private static final Logger log = Logger
      .getLogger(FacebookRedirectServlet.class.getName());

  /**
   * It handles requests from Facebook after successful or failed feed post.
   */
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    log.info(req.getRequestURI());
    log.info(req.getQueryString());
    String page = req.getParameter("page");
    String place = req.getParameter("place");
    String token = req.getParameter("token");
    String postId = req.getParameter(Constants.FACEBOOK_POST_ID);
    // Posted already.
    if (postId != null) {
      //token = new ServerUrlUtil().stripParam(Constants.AUTO_CHECKIN, token);
      checkin(token, postId);
    }
    String redirectUrl = getRedirectUrl(page, place, token);
    log.info(redirectUrl);

    resp.sendRedirect(redirectUrl);
  }

  private void checkin(String token, String postId) {
    ServerUtil util = new ServerUtil();
    String merchant = util.getParameterFromToken(Constants.MERCHANT, token);
    String user = util.getParameterFromToken(Constants.USER, token);
    Checkin checkin = new Checkin();
    checkin.setMerchantId(merchant);
    checkin.setUserId(user);
    checkin.setCreationTime(new Date());
    GenericDao<Checkin> dao = new GenericDao<Checkin>(Checkin.class);
    dao.put(checkin);
    log.info(checkin.toString());
  }

  private String getRedirectUrl(String page, String place, String token) {
    if (!Strings.isNullOrEmpty(page) && page.indexOf('/') == 0) {
      page = page.substring(1);
    }
    return "/" + page + "#" + place + ":" + token;
  }
}
